package com.gdth.service;

import java.io.IOException;

import com.gdth.bank.BankApplication;
import com.gdth.utils.ToolUtil;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;

public class PhoneMediaPlayer {
	private MediaPlayer mMediaPlayer;

	private AudioManager mAudioMgr;

	private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = null;
	
	public PhoneMediaPlayer(){
		this.mMediaPlayer = new MediaPlayer();
		
		//Build.VERSION.SDK_INT表示当前SDK的版本，Build.VERSION_CODES.ECLAIR_MR1为SDK 7版本 ，
		//因为AudioManager.OnAudioFocusChangeListener在SDK8版本开始才有。
		if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1){
			mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
				@Override
				public void onAudioFocusChange(int focusChange) {
					if(focusChange == AudioManager.AUDIOFOCUS_LOSS){
						//失去焦点之后的操作
						if(mMediaPlayer.isPlaying()){
							mMediaPlayer.pause();
						}
					}else if(focusChange == AudioManager.AUDIOFOCUS_GAIN){
						//获得焦点之后的操作
						mMediaPlayer.start();
					}
				}
			};
		}
		
	}
	
	/**
	 * 设置音乐路径，并启动音乐
	 * @param url
	 */
	public void setMusic(String url){
		try {
			String path = ToolUtil.getFilePath(url + ".3gp");
			mMediaPlayer.setDataSource(path);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		startMusic();
	}
	
	public void startMusic(){

		requestAudioFocus();
	}
	
	public void stopMusic(){
		mMediaPlayer.stop();
	}
	
	public void pauseMusic(){
		mMediaPlayer.pause();
	}
	
	private void requestAudioFocus() {
		if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.ECLAIR_MR1){
			return;
		}
		if (mAudioMgr == null)
			mAudioMgr = (AudioManager) BankApplication.mInstance.getBaseContext().getSystemService(Context.AUDIO_SERVICE);
		if (mAudioMgr != null) {
			int ret = mAudioMgr.requestAudioFocus(mAudioFocusChangeListener,
					AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
			if (ret != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
			}
		}

	}
	
}
